package middleware

import (
	"log"
	"net/http"
	"strings"
	"time"
	"xiaoniu-registry/internal/metrics"
	"xiaoniu-registry/internal/response"
)

// CORS 跨域中间件
func CORS(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
		w.Header().Set("Access-Control-Max-Age", "86400")

		// 处理预检请求
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusOK)
			return
		}

		next.ServeHTTP(w, r)
	})
}

// Logging 日志中间件
func Logging(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()

		// 创建一个包装的ResponseWriter来捕获状态码
		wrapped := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}

		// 统计请求
		metrics.IncrementTotalRequests()
		if strings.HasPrefix(r.URL.Path, "/api/beat") {
			metrics.IncrementHeartbeatRequests()
		} else if strings.HasPrefix(r.URL.Path, "/api/") {
			metrics.IncrementAPIRequests()
		}

		next.ServeHTTP(wrapped, r)

		duration := time.Since(start)
		log.Printf("%s %s %d %v %s", r.Method, r.URL.Path, wrapped.statusCode, duration, r.RemoteAddr)
	})
}

// responseWriter 包装http.ResponseWriter以捕获状态码
type responseWriter struct {
	http.ResponseWriter
	statusCode int
}

func (rw *responseWriter) WriteHeader(code int) {
	rw.statusCode = code
	rw.ResponseWriter.WriteHeader(code)
}

// Recovery 恢复中间件，捕获panic
func Recovery(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if err := recover(); err != nil {
				log.Printf("Panic recovered: %v", err)
				response.InternalError(w, "服务器内部错误")
			}
		}()
		next.ServeHTTP(w, r)
	})
}

// RateLimiting 简单的速率限制中间件
func RateLimiting(next http.Handler) http.Handler {
	// 简单的内存存储，生产环境应该使用Redis等
	clientRequests := make(map[string][]time.Time)
	maxRequests := 100 // 每分钟最大请求数
	window := time.Minute

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		clientIP := r.RemoteAddr
		now := time.Now()

		// 清理过期的请求记录
		if requests, exists := clientRequests[clientIP]; exists {
			var validRequests []time.Time
			for _, reqTime := range requests {
				if now.Sub(reqTime) < window {
					validRequests = append(validRequests, reqTime)
				}
			}
			clientRequests[clientIP] = validRequests
		}

		// 检查是否超过限制
		if len(clientRequests[clientIP]) >= maxRequests {
			response.Error(w, http.StatusTooManyRequests, 429, "请求过于频繁，请稍后再试")
			return
		}

		// 记录当前请求
		clientRequests[clientIP] = append(clientRequests[clientIP], now)

		next.ServeHTTP(w, r)
	})
}

// Chain 中间件链
func Chain(middlewares ...func(http.Handler) http.Handler) func(http.Handler) http.Handler {
	return func(final http.Handler) http.Handler {
		for i := len(middlewares) - 1; i >= 0; i-- {
			final = middlewares[i](final)
		}
		return final
	}
}
